<route lang="json5">
	{
	needLogin: true,
	style: {
	navigationStyle: 'custom',
	navigationBarTitleText: '创建讨论组',
	},
	}
</route>
<template>
	<view class="group-setting">
		<!-- 顶部导航栏 -->
		<wd-navbar title="创建讨论组" left-arrow placeholder @click-left="goBack"
			custom-style="background: #fff; border-bottom: none;" fixed safeAreaInsetTop></wd-navbar>

		<!-- 群组基本信息 -->
		<view class="bg-white mt-0 mb-24rpx mt-24rpx ml-24rpx mr-24rpx border-rd-[10px_10px_10px_10px]">
			<wd-cell>
				<template #title>
					<view class="flex items-center w-full">
						<view class="w-96rpx h-96rpx">
							<image class="w-96rpx h-96rpx"
								:src="groupInfo.headImage ? groupInfo.headImage : '/static/images/course/group.png'"
								mode="scaleToFill" />
						</view>
					</view>
				</template>
				<view class="flex flex-col items-end">
					<view
						class="w-130rpx h-46rpx bg-[#3670F7] text-22rpx text-[#FFFFFF] lh-46rpx text-center border-rd-10rpx"
						@click="handleUpload">
						去上传
					</view>
					<view class="text-22rpx text-[#999999] lh-30rpx text-center border-rd-10rpx mt-18rpx">
						只能上传jpg/png格式文件
					</view>
				</view>
			</wd-cell>
			<wd-cell-group>
				<wd-input custom-input-class="text-right" type="text" label="群名称" :maxlength="30"
					v-model="groupInfo.showGroupName" placeholder="请输入群名称" />
				<wd-cell title="我的群身份" :value="myNickname" />
			</wd-cell-group>
		</view>

		<!-- 成员列表 -->
		<view
			class="members bg-white mt-0 mb-24rpx ml-24rpx mr-24rpx pt-31rpx pl-35rpx pb-60rpx pr-40rpx border-rd-[10px_10px_10px_10px]">
			<view class="flex justify-between items-center mb-24rpx">
				<text class="section-title">组成员</text>
				<text class="member-count">{{ groupInfo.memberList.length }}人</text>
			</view>

			<view class="member-grid">
				<view v-for="member in groupInfo.memberList" :key="member.studentId" class="member-item">
					<wd-img class="member-avatar w-92rpx h-92rpx" :src="member.headshot ? member.headshot : 'null'">
						<template #error>
							<view class="error-wrap">{{ member.name }}</view>
						</template>
					</wd-img>
					<view class="member-name">{{ member.name }}</view>
					<view v-if="member.role" class="member-role">{{ member.role }}</view>
				</view>
				<view class="member-action" @click="handleAddMember">
					<image class="action-icon" src="/static/images/course/add-user.png" mode="scaleToFill" />
					<text class="action-text">邀请</text>
				</view>
				<view class="member-action" @click="handleRemoveMember">
					<image class="action-icon" src="/static/images/course/remove-user.png" mode="scaleToFill" />
					<text class="action-text">移除</text>
				</view>
			</view>
		</view>

		<!-- 群组主题 -->
		<view
			class="bg-white mt-0 mb-24rpx ml-24rpx mr-24rpx border-rd-[10px_10px_10px_10px] pb-60rpx pt-31rpx pl-35rpx">
			<wd-cell-group>
				<view class="mb-12rpx"><text class="section-title">组主题</text></view>
				<wd-textarea v-model="groupInfo.groupTopic" :maxlength="500" clearable auto-height no-border />
			</wd-cell-group>
		</view>

		<!-- 创建讨论组 -->
		<view class="fixed bottom-34rpx left-0rpx w-full">
			<view class="px-24rpx">
				<wd-button block size="large" @click="handleSubmitGroup" custom-class="dismiss-group">
					创建讨论组
				</wd-button>
			</view>
		</view>

		<!-- 修改结果页面 -->
		<uni-popup ref="popup" type="center">
			<template #default>
				<view
					style="background-color: white; border-radius: 20rpx; padding-left: 80rpx; padding-right: 80rpx; padding-bottom: 40rpx;">

					<!-- 图片区域 -->
					<view class="flex justify-center mb-[20rpx]">
						<image :src="'/static/images/login/success.png'" class="w-[320rpx] h-[320rpx]"
							mode="aspectFit" />
					</view>

					<!-- 标题区域 -->
					<view class="mb-[45rpx] text-center">
						<view class="text-[40rpx] font-bold color-#333333 mb-[16rpx]">
							创建成功
						</view>
						<view class="text-[28rpx] color-#999999">
							讨论组创建成功
						</view>
					</view>

					<!-- 按钮 -->
					<wd-button size="large" type="primary" block class="h-[88rpx] w-[400rpx] rounded-full"
						@click="handleResultButtonClick">
						确认
					</wd-button>

				</view>

			</template>

		</uni-popup>

	</view>
</template>

<script setup lang="ts">
	import { findGroupInfo, membersGroupInfo, createGroup } from '@/service/edu/group'
	import { useGroupStore, useUserStore } from '@/store'
	import { ref } from 'vue'
	const popup = ref(null);

	const groupInfo = ref({
		courseId: '',
		groupId: '',
		name: '',
		showGroupName: '',
		headImage: '',
		memberCount: 0,
		memberList: [], // 成员列表
		groupTopic: '',
	})
	const groupStore = useGroupStore()
	onLoad(() => {
		const pages = getCurrentPages()
		const currentPage : any = pages[pages.length - 1]
		const options = currentPage.$page?.options || currentPage?.options || currentPage.$route.query
		if (options) {
			groupInfo.value.courseId = options.courseId
		}
	})
	onShow(() => {
		if (groupStore.createType) {
			groupInfo.value.memberList = groupStore.createFriendIds
		}
	})

	const myNickname = ref('教师')

	const goBack = () => {
		groupStore.setCreateType(false)
		groupStore.setFriendIds([])
		// uni.navigateBack()
	}

	const handleAddMember = () => {
		uni.navigateTo({
			url: `/pages/group/member-select?courseId=${groupInfo.value.courseId}&create=1`,
		})
	}

	const handleRemoveMember = () => {
		if (groupInfo.value.memberList.length > 0) {
			uni.navigateTo({
				url: `/pages/group/member-remove?groupId=${groupInfo.value.groupId}&create=1`,
			})
		} else {
			uni.showToast({
				title: '暂无成员',
				icon: 'none',
			})
		}
	}

	function handleUpload() {
		uni.chooseImage({
			count: 1, // 默认9
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera '], // 从相册选择
			success: async function (res) {
				console.log(JSON.stringify(res.tempFilePaths))
				const uploadRes = await uploadFile(res.tempFilePaths[0])
				groupInfo.value.headImage = uploadRes.url
			},
		})
	}
	// 上传文件
	function uploadFile(filePath : string) : Promise<any> {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: '/resource/oss/upload', // 替换为实际的上传接口
				filePath,
				name: 'file',
				success: (res) => {
					const data = JSON.parse(res.data)
					if (data.code === 200) {
						resolve(data.data)
					} else {
						reject(new Error(data.msg))
					}
				},
				fail: reject,
			})
		})
	}
	const userStore = useUserStore()
	const handleSubmitGroup = () => {
		if (!groupInfo.value.showGroupName?.trim()) {
			uni.showToast({
				title: '请输入群名称',
				icon: 'none',
			})
			return false
		}
		if (!groupInfo.value.headImage?.trim()) {
			uni.showToast({
				title: '请上传组头像',
				icon: 'none',
			})
			return false
		}
		if (groupInfo.value.memberList.length === 0) {
			uni.showToast({
				title: '请选择成员',
				icon: 'none',
			})
			return false
		}
		uni.showModal({
			title: '提示',
			content: '确认创建该群聊吗？',
			confirmText: '确认创建',
			success: function (res) {
				if (res.confirm) {
					const memberList = groupInfo.value.memberList.map((item) => item.studentId) // 群组成员
					memberList.push(userStore.userInfo.userId)
					// 调用创建群聊API
					createGroup({
						name: groupInfo.value.showGroupName, // 群名称
						ownerId: userStore.userInfo.userId, // 群主id
						headImage: groupInfo.value.headImage, // 头像
						headImageThumb: groupInfo.value.headImage, // 头像缩略图
						notice: '', // 群公告
						remarkNickName: '', // 用户在群显示昵称
						showNickName: '', // 群内显示名称
						showGroupName: groupInfo.value.showGroupName, // 群名显示名称
						remarkGroupName: groupInfo.value.showGroupName, // 群名备注
						groupTopic: groupInfo.value.groupTopic, // 群主题
						dissolve: false, // 是否已解散
						quit: false, // 是否已退出
						memberList, // 群组成员
						courseId: groupInfo.value.courseId, // 课程id
					}).then(async (res) => {
						if (res.code === 200) {
							groupStore.setCreateType(false)
							groupStore.setFriendIds([])
							// uni.showToast({
							//   title: '创建群聊成功',
							//   icon: 'success',
							// })
							popup.value.open('center');
							await groupStore.loadGroup()
							// setTimeout(() => {
							// 	uni.navigateBack()
							// }, 500)
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
							})
						}
					})
				} else if (res.cancel) {
					console.log('用户点击取消')
				}
			},
		})
	}

	// 结果页面按钮点击
	const handleResultButtonClick = () => {
		uni.navigateBack({
			delta: 1,
		})
	}
</script>

<style lang="scss">
	.group-setting {
		min-height: 100vh;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		background-color: #f5f5f5;
	}

	.error-wrap {
		width: 100%;
		height: 100%;
		overflow: hidden;
		font-size: 26rpx;
		line-height: 92rpx;
		color: #f6f9fe;
		text-align: center;
		background: #3670f7;
		border-radius: 12rpx 12rpx 12rpx 12rpx;
	}

	.group-info {
		.group-avatar {
			width: 96rpx;
			height: 96rpx;
			background: #d8d8d8;
			border: 1rpx solid #d8d8d8;
			border-radius: 16rpx;
		}

		.group-name {
			margin-top: 4rpx;
			margin-bottom: 4rpx;
			font-size: 34rpx;
			font-weight: bold;
			line-height: 47rpx;
			color: #3d3d3d;
		}

		.group-id {
			font-size: 26rpx;
			line-height: 38rpx;
			color: #767676;
		}
	}

	.section-title {
		font-size: 30rpx;
		font-weight: bolder;
		color: #3d3d3d;
	}

	.member-count {
		font-size: 26rpx;
		color: #999;
	}

	.member-grid {
		display: grid;
		grid-template-columns: repeat(5, 1fr);
		gap: 24rpx;
	}

	.member-item {
		display: flex;
		flex-direction: column;
		align-items: center;

		.member-avatar {
			margin-bottom: 12rpx;
		}

		.member-name {
			width: 100%;
			font-size: 24rpx;
			font-weight: 500;
			line-height: 34rpx;
			color: #767c89;
			text-align: center;
			@apply truncate;
		}

		.member-role {
			margin-top: 4rpx;
			font-size: 22rpx;
			color: #999;
		}
	}

	.member-action {
		display: flex;
		flex-direction: column;
		align-items: center;

		.action-icon {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 92rpx;
			height: 92rpx;
			margin-bottom: 12rpx;
			font-size: 44rpx;
			color: #999;
			border-radius: 12rpx;
		}

		.action-text {
			font-size: 24rpx;
			color: #767c89;
		}
	}

	/* #ifdef H5 */
	:deep(.wd-navbar) {
		padding-top: 0;
	}

	/* #endif */
	/* #ifdef MP */
	:deep(.wd-navbar) {
		padding-top: var(--status-bar-height);
	}

	/* #endif */
	.dismiss-group {
		color: #ffffff !important;
		background: linear-gradient(90deg, #20a4ff 2%, #0d53ff 100%) !important;
		border-radius: 50rpx !important;
	}
</style>